import { Product } from "@/typings";

interface Cert {
  products: Product[];
  numActive: boolean;
  [index: string]: any;
}
export default {
  namespaced: true,
  state: {
    products: [],
    numActive: false,
  } as Cert,
  mutations: {
    reduceProductCount(state: Cert, product: Product) {
      //如果购买数量为1的时候按- 则删除
      if (product.count == 1) {
        state.commit("removeProduct", product);
      } else {
        product.count--;
      }
    },
    plusProductCount(state: Cert, product: Product) {
      product.count++;
    },
    checkboxChange(state: Cert, id: string) {
      const res = state.products.filter((x) => x.id == id);
      res[0].checked = !res[0].checked;
    },
    pushToCert(state: Cert, product: Product) {
      const res = state.products.filter((x) => x.id == product.id);
      //  如果购物车中已经有这个产品，则只需要自增count，否则需要加入购物车
      if (res.length <= 0) {
        product.count++;
        product.checked = true;
        state.products.push(product);
      } else {
        // 自增购物车中的商品对象的count，而不是自增product的count。虽然和productid一样
        res[0].count++;
      }
      // 购物车数字跳动
      state.numActive = true;
      setTimeout(() => {
        state.numActive = false;
      }, 600);
    },
    removeProduct(state: Cert, product: Product) {
      state.products = state.products.filter((x) => {
        return x.id != product.id;
      });
    },
    clearCert(state: Cert) {
      state.products.forEach((prod) => {
        prod.count = 0;
        prod.checked = false;
      });
      state.products = [];
    },
    fullChoose(state: Cert, data: any) {
      state.products.forEach((x) => (x.checked = data.value));
    },
  },
};
